/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tcloudclient;

import api.Beans.UserLogin;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import security.Md5;
import tcloudclient.UploadManager.ConnectionException;
import tcloudclient.UploadManager.ConnectionManagerInterface;
import tcloudclient.contex.Context;
import tcloudclient.settings.ApplicationSettings;
import tcloudclient.settings.AutoLoginSetting;
import tcloudclient.settings.XmlLoaderSaver;

/**
 *
 * @author Tomas
 */
public class SetupJDialog extends javax.swing.JDialog {

    private JFileChooser jFileChooserSyncFolder;
    private ConnectionManagerInterface connectioManager;
    private UserLogin user;
    private String syncPath;
    private SetupFinishedInterface setupFinish;

    /**
     * Creates new form SetupJDialog
     */
    public SetupJDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldUserName = new javax.swing.JTextField();
        jPasswordFieldPassword = new javax.swing.JPasswordField();
        jSeparator1 = new javax.swing.JSeparator();
        jButtonLogin = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldSelectFolderPath = new javax.swing.JTextField();
        jButtonSelectFolder = new javax.swing.JButton();
        jButtonFinish = new javax.swing.JButton();
        jLabelError = new javax.swing.JLabel();
        jLabelInfo = new javax.swing.JLabel();
        jCheckBoxAutoLogin = new javax.swing.JCheckBox();

        jPasswordField1.setText("jPasswordField1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Setup");
        setLocationByPlatform(true);

        jLabel1.setLabelFor(jTextFieldUserName);
        jLabel1.setText("Username");

        jLabel2.setLabelFor(jPasswordFieldPassword);
        jLabel2.setText("Password");

        jButtonLogin.setText("Login");
        jButtonLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLoginActionPerformed(evt);
            }
        });

        jLabel3.setText("Sync folder");

        jTextFieldSelectFolderPath.setEditable(false);
        jTextFieldSelectFolderPath.setToolTipText("");

        jButtonSelectFolder.setText("...");
        jButtonSelectFolder.setToolTipText("Select sync folder");
        jButtonSelectFolder.setEnabled(false);
        jButtonSelectFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSelectFolderActionPerformed(evt);
            }
        });

        jButtonFinish.setText("Finish");
        jButtonFinish.setEnabled(false);
        jButtonFinish.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFinishActionPerformed(evt);
            }
        });

        jLabelError.setForeground(new java.awt.Color(255, 0, 0));

        jLabelInfo.setForeground(new java.awt.Color(0, 204, 0));

        jCheckBoxAutoLogin.setSelected(true);
        jCheckBoxAutoLogin.setText("Auto login");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextFieldSelectFolderPath, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonSelectFolder, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButtonFinish)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(2, 2, 2)
                                        .addComponent(jLabel1))
                                    .addComponent(jLabel2))
                                .addGap(28, 28, 28)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jPasswordFieldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextFieldUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jCheckBoxAutoLogin)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButtonLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 24, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                            .addComponent(jLabelError, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelInfo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPasswordFieldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelError, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonLogin)
                    .addComponent(jCheckBoxAutoLogin))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldSelectFolderPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonSelectFolder))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonFinish)
                .addGap(67, 67, 67))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSelectFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelectFolderActionPerformed
        // TODO add your handling code here:
        jFileChooserSyncFolder = new JFileChooser();

        jFileChooserSyncFolder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int vysledek = jFileChooserSyncFolder.showOpenDialog(this);
        if (vysledek == JFileChooser.APPROVE_OPTION) {
            File selectedFile = jFileChooserSyncFolder.getSelectedFile();

            jTextFieldSelectFolderPath.setText(selectedFile.getAbsolutePath());
            syncPath = selectedFile.getAbsolutePath();
            jButtonFinish.setEnabled(true);
        }
    }//GEN-LAST:event_jButtonSelectFolderActionPerformed

    private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLoginActionPerformed
        
            // TODO add your handling code here:
            String userName = jTextFieldUserName.getText();
            String password = new String(jPasswordFieldPassword.getPassword());

            if (userName == null || password == null) {
                jLabelError.setText("Username and password is required!");
            } else {
            try {
                String passMd5 = Md5.MD5(password);
                user = connectioManager.login(userName, passMd5);
                if (user == null) {
                    jLabelError.setText("Bad username or password! Try it again.");
                } else {
                    jButtonLogin.setEnabled(false);
                    jTextFieldUserName.setEditable(false);
                    jPasswordFieldPassword.setEditable(false);
                    jLabelInfo.setText("Login sucessful!");
                    jButtonSelectFolder.setEnabled(true);
                    if (jTextFieldSelectFolderPath.getText() != null) {
                        jButtonFinish.setEnabled(true);
                        syncPath = jTextFieldSelectFolderPath.getText();
                    }
                }
            } catch (ConnectionException ex) {
                Logger.getLogger(SetupJDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
            }        
    }//GEN-LAST:event_jButtonLoginActionPerformed

    private void jButtonFinishActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFinishActionPerformed
        // TODO add your handling code here: 
        setupFinish.setupSucessFul(user, syncPath);
        AutoLoginSetting loginSetting;
        if (jCheckBoxAutoLogin.isSelected()) {
            String password = new String(jPasswordFieldPassword.getPassword());
            String passMd5 = Md5.MD5(password);
            loginSetting = new AutoLoginSetting(jTextFieldUserName.getText(), passMd5, jCheckBoxAutoLogin.isSelected());
        } else {
            loginSetting = new AutoLoginSetting(jTextFieldUserName.getText(), null, false);
        }
        ApplicationSettings applicationSettings = Context.getInstance().getApplicationSettings();
        if (applicationSettings == null) {
            applicationSettings = new ApplicationSettings();
            applicationSettings.setAccHeaderVetsion(0);
            applicationSettings.setUser(user);
            applicationSettings.setRegisterDir(new File(syncPath));
        }
        Context.getInstance().setApplicationSettings(applicationSettings);
        XmlLoaderSaver.saveAppSettings();
        XmlLoaderSaver.saveLoginSetting(loginSetting);
        
        this.setVisible(false);
    }//GEN-LAST:event_jButtonFinishActionPerformed

    @Override
    public void setVisible(boolean visible) {
        setUserLogin();
        super.setVisible(visible);
    }

    public ConnectionManagerInterface getConnectioManager() {
        return connectioManager;
    }

    public void setConnectioManager(ConnectionManagerInterface connectioManager) {
        this.connectioManager = connectioManager;
    }

    public UserLogin getUser() {
        return user;
    }

    public String getSyncPath() {
        return syncPath;
    }

    public void setSetupFinish(SetupFinishedInterface setupFinish) {
        this.setupFinish = setupFinish;
    }

    private void setUserLogin() {
        ApplicationSettings applicationSettings = Context.getInstance().getApplicationSettings();
        if (applicationSettings != null) {
            jTextFieldUserName.setText(applicationSettings.getUser().getUserName());
            jTextFieldSelectFolderPath.setText(applicationSettings.getRegisterDir().getAbsolutePath());

        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonFinish;
    private javax.swing.JButton jButtonLogin;
    private javax.swing.JButton jButtonSelectFolder;
    private javax.swing.JCheckBox jCheckBoxAutoLogin;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelError;
    private javax.swing.JLabel jLabelInfo;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPasswordField jPasswordFieldPassword;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextFieldSelectFolderPath;
    private javax.swing.JTextField jTextFieldUserName;
    // End of variables declaration//GEN-END:variables
}
